const axios = require("axios");
const { dify } = require("../../config")

class StepNameWorkflowRunner {
    constructor() {
        this.url = dify.stepName.url;
        this.token = dify.stepName.token;
    }

    async runWorkflow(inputs, user) {
        const data = JSON.stringify({
            "inputs": inputs,
            "response_mode": "blocking",
            "user": user
        });

        const config = {
            method: "post",
            maxBodyLength: Infinity,
            url: this.url,
            headers: {
                "Authorization": `Bearer ${this.token}`,
                "Content-Type": "application/json"
            },
            data: data,
        };
        if (config.url.startsWith("https://")) {
            config.httpsAgent = new (require("https").Agent)({ rejectUnauthorized: false });
        }
        try {
            const response = await axios.request(config);
            return response.data;
        } catch (error) {
            return {
                "data": {
                    "outputs": {
                    }
                }
            };
        }
    }

    /**
     * 
     * @param {string} apis 
     * @returns {Promise<string>}
     */
    async getStepNameByApis(apis) {
        let result = await this.runWorkflow({ "apis": apis }, "automated-performance-platform");
        let stepName = result.data.outputs.stepName;
        return stepName;
    }
}

module.exports = StepNameWorkflowRunner;